package com.neusoft.elmboot.controller;


import com.neusoft.elmboot.common.Result;
import com.neusoft.elmboot.dto.FoodReqDto;
import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    private FoodService foodService;


    @RequestMapping("/listFoodByBusinessId")
    public List<Food> listFoodByBusinessId(Food food) throws Exception{
        return foodService.listFoodByBusinessId(food.getBusinessId());
    }

    /**
     * 食品列表查询（带分页）
     * @return
     */
    @GetMapping("/list")
//    @PreAuthorize("hasRole('user')")
    public Result list(FoodReqDto params) {
        // 调用业务层（service层）来处理业务逻辑！
        List<Food> foodsList = foodService.getFoodsList(params);
        Long total = foodService.getFoodsCount(params);

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("data",foodsList);
        retMap.put("total", total);


        return Result.success(retMap,"食品列表查询成功！");
    }


    /**
     * 新增食品
     * @return
     */
    @PostMapping("/create")
    public Result add(@RequestBody FoodReqDto params) {
        System.out.println("-----------food/create...");
        // 调用业务层（service层）来处理业务逻辑！
        Integer x = foodService.addFood(params);

        return Result.success(x,"新增食品成功！");
    }

    /**
     * 根据食品编号查看食品详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result detail(Integer id) {
        Food food = foodService.getFoodByFoodId(id);
        return Result.success(food,"查看食品详情成功");
    }


    /**
     * 更新食品接口
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody FoodReqDto params) {
        System.out.println("-----------food/update...");
        // 校验参数合法性  (也可以使用validator验证框架)
        if (null == params.getFoodName() || params.getFoodName().trim().length() == 0) {
            return Result.fail(500,"食品名称不可以为空！");
        } else if (params.getFoodName().trim().length() > 30) {
            return Result.fail(500,"食品名称长度必须小于30！");
        }


        // 调用业务层（service层）来处理业务逻辑！
        Integer x = foodService.updateFood(params);

        return Result.success(params.getFoodId(),"更新食品成功！");
    }

    /**
     * 根据食品编号删除食品
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable Integer id) {
        foodService.deleteFood(id);
        return Result.success(id,"食品删除成功！");
    }






}
